package com.org.manhu.chargehelper.ui;

import java.io.File;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.w3c.dom.UserDataHandler;

import com.org.manhu.chargehelper.ChargeApplication;
import com.org.manhu.chargehelper.R;
import com.org.manhu.chargehelper.broadcastreceiver.UpdateMoneyReceiver;
import com.org.manhu.chargehelper.broadcastreceiver.UpdateNickNameReceiver;
import com.org.manhu.chargehelper.constant.Constant;
import com.org.manhu.chargehelper.custom.ImageBigPopwindow;
import com.org.manhu.chargehelper.custom.RoundCornersImageView;
import com.org.manhu.chargehelper.down.DownloadProgressListener;
import com.org.manhu.chargehelper.down.FileDownloader;
import com.org.manhu.chargehelper.download.DownloadManager;
import com.org.manhu.chargehelper.download.DownloadTask;
import com.org.manhu.chargehelper.download.UpdateListener;
import com.org.manhu.chargehelper.tools.ApkInfoUtils;
import com.org.manhu.chargehelper.tools.AppManager;
import com.org.manhu.chargehelper.tools.DeviceInfo;
import com.org.manhu.chargehelper.tools.FileUtil;
import com.org.manhu.chargehelper.tools.JsonUtil;
import com.org.manhu.chargehelper.tools.LoadImage;
import com.org.manhu.chargehelper.tools.LogUtils;
import com.org.manhu.chargehelper.tools.NetUtils;
import com.org.manhu.chargehelper.tools.SharedPreferncesUtil;
import com.org.manhu.chargehelper.tools.StringUtils;
import com.org.manhu.chargehelper.tools.ToastUtils;
import com.org.manhu.chargehelper.webservice.AsyncProcessData;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @文件名：DetialActivity.java
 * @包名：com.org.manhu.chargehelper.ui
 * @作者：李朋辉 @QQ：892839211
 * @创建时间：2015年2月5日 上午9:48:25
 *
 * @描述：服务器的数据的应用详情
 */
public class NetDetialActivity extends Activity implements OnClickListener {

	private ImageView backIv, userInfoMoreIv;
	private Button cashOutBtn, exchangeBtn;

	private LinearLayout galleryArray;
	Integer[] images = { R.drawable.pic01, R.drawable.pic02, R.drawable.pic03,
			R.drawable.pic04, R.drawable.pic05 };
	DecimalFormat df = new DecimalFormat("0.00");

	private RoundCornersImageView appIconIv;
	private TextView appNameTv, awardTv, sizeTv;
	private Button downBtn;
	private TextView appSummaryTv;

	private TextView userNameTv, awardNumTv;
	private LinearLayout progressLayout;
	private ProgressBar downProgressBar;
	private TextView downPercentTv;

	private String appId;

	private AsyncProcessData request;
	private ProgressDialog mPd;
	private Map<String, String> map;
	private UpdateNickNameReceiver mReceiver;
	private UpdateMoneyReceiver receivers;
	private ImageBigPopwindow imagebigPopwindow;

	private String channelId;
	private String devId;

	private int max;

	private DownloadTask mDownloadTask = null;

	private boolean mIsPause = true;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			String json = msg.getData().getString("jsonStr");
			if (Constant.GET_APP_INFO.equals(msg.obj.toString())) {
				map = JsonUtil.parseToMap(json);
				if (map != null) {
					setData(map);
				}
			} else if (Constant.USER_SETUP_RES.equals(msg.obj.toString())) {

			} else if (Constant.USER_DOWN_RES.equals(msg.obj.toString())) {
				LogUtils.d("TAG", "下载资源：：" + msg.getData().getString("jsonStr"));
				Map<String, String> feedBackMap = JsonUtil.parseAll(json);
				if (feedBackMap != null) {
					if (feedBackMap.get("Code").equals("0")) {
						clientInit();
					}
				} else {
					userDownRes();
				}
			} else if (Constant.CLIENT_INIT.equals(msg.obj.toString())) {
				Map<String, String> initMap = JsonUtil.parseAll(json);
				if (initMap != null) {
					ChargeApplication.updateInitInfo(initMap);
					userDownRes();
				} else {
					clientInit();
				}
			}
		}

	};

	private void setData(Map<String, String> map) {
		// TODO Auto-generated method stub

		mPd.dismiss();

		downBtn.setVisibility(View.VISIBLE);

		LoadImage.LoadBigPic(map.get("IcoUrl"), appIconIv);
		appNameTv.setText(map.get("AppName"));
		awardTv.setText("安装奖励：" + map.get("UserPrice") + "元");
		String size = df.format(Float.parseFloat(map.get("Size"))
				/ (1024 * 1024))
				+ "M";
		String tag = map.get("Tag");
		if (!TextUtils.isEmpty(tag) && tag != null) {
			sizeTv.setText(map.get("Tag") + " | " + size);
		} else {
			sizeTv.setText(size);
		}

		appSummaryTv.setText(map.get("Digest"));

		String packageName = map.get("PackageName");
		if (ApkInfoUtils.isInstalled(packageName)) {
			if (Integer.parseInt(map.get("VerCode")) > ApkInfoUtils
					.getVersionCode(packageName)) {
				downBtn.setText("更新");
			}else{
				downBtn.setText("打开");
			}
		} else {
			if (FileUtil.isFileExit(ChargeApplication.APP_ROOT
					+ FileUtil.getFileName(map.get("DownUrl")))) {
				downBtn.setText("安装");
			}
		}

		List<String> list = JsonUtil.parseImageList(map.get("ImgList"));
		imagebigPopwindow = new ImageBigPopwindow(NetDetialActivity.this, list);
		for (int i = 0; i < list.size(); i++) {
			galleryArray.addView(insertImage(list.get(i), i));
		}

		if (DownloadManager.getInstance().getDownloadTask(map.get("DownUrl")) != null) {
			if (DownloadManager.getInstance().isTaskPause(map.get("DownUrl"))) {
				downBtn.setText("开始");
				mIsPause = true;
			} else {
				progressLayout.setVisibility(View.VISIBLE);
				downBtn.setText("暂停");
				mIsPause = false;
			}
			mDownloadTask = DownloadManager.getInstance().getDownloadTask(
					map.get("DownUrl"));
			setUpdateListener();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_details);

		appId = getIntent().getStringExtra("appid");
		request = new AsyncProcessData();
		getAppDetialInfo();

		mPd = new ProgressDialog(this);
		mPd.setMessage("正在获取数据，请耐心等待……");
		mPd.setCanceledOnTouchOutside(false);
		mPd.show();

		init();
		mReceiver = new UpdateNickNameReceiver(userNameTv);
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constant.ACTION_UPDATE_NICKNAME);
		registerReceiver(mReceiver, filter);

		receivers = new UpdateMoneyReceiver(awardNumTv);
		IntentFilter filters = new IntentFilter();
		filter.addAction(Constant.ACTION_UPDATE_MONEY);
		registerReceiver(receivers, filters);
	}

	/**
	 * @描述：
	 */
	private void getAppDetialInfo() {
		if (NetUtils.isConnected(this)) {
			request.getRequestData(mHandler, Constant.GET_APP_INFO, "appId",
					appId);
		} else {
			ToastUtils.showShort(getApplicationContext(), "网络异常，请稍检查网络");
		}
	}

	/**
	 * @描述： 客户端初始化，获取AuthKey
	 */
	private void clientInit() {
		if (NetUtils.isConnected(this)) {
			if (Constant.IS_USE_BOXINFO) {
				channelId = SharedPreferncesUtil.getBoxInfo(this,
						Constant.SP_BOX_CHANNELID);
				devId = SharedPreferncesUtil.getBoxInfo(this,
						Constant.SP_BOX_DEVID);
			} else {
				channelId = "0";
				devId = "0";
			}
			request.getRequestData(mHandler, Constant.CLIENT_INIT, "AuthKey",
					"", "Imei", DeviceInfo.getIMEI(), "Imsi",
					DeviceInfo.getIMSI(), "AndroidId",
					DeviceInfo.getAndroidID(), "PhoneTypeId",
					DeviceInfo.getDeviceModel(), "ChannelId", channelId,
					"DevId", devId);
		} else {
			ToastUtils.showShort(this, "网络异常，请稍检查网络");
		}
	}

	/**
	 * @描述：用户下载资源
	 */
	private void userDownRes() {
		if (NetUtils.isConnected(this)) {
			request.getRequestData(mHandler, Constant.USER_DOWN_RES, "AuthKey",
					ChargeApplication.getInitInfo().get("AuthKey"), "ResId",
					appId);
		} else {
			ToastUtils.showShort(this, "网络异常，请稍检查网络");
		}

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		awardNumTv.setText(SharedPreferncesUtil.getMoney(this) + "");
		userNameTv.setText(SharedPreferncesUtil.getNickName(this));
		if (ApkInfoUtils.isInstalled(map.get("PackageName"))) {
			downBtn.setText("打开");
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(mReceiver);
		unregisterReceiver(receivers);
	}

	/**
	 * @描述： 初始化控件，设置监听
	 */
	private void init() {
		AppManager.getAppManager().addActivity(this);

		backIv = (ImageView) findViewById(R.id.title_back);
		cashOutBtn = (Button) findViewById(R.id.tixian_btn);
		cashOutBtn.setVisibility(View.GONE);
		exchangeBtn = (Button) findViewById(R.id.exchange_btn);
		userInfoMoreIv = (ImageView) findViewById(R.id.user_info_more);
		galleryArray = (LinearLayout) findViewById(R.id.galleryArray);
		userNameTv = (TextView) findViewById(R.id.user_name);
		awardNumTv = (TextView) findViewById(R.id.user_award_num);
		awardNumTv.setText(SharedPreferncesUtil.getMoney(this) + "");
		userNameTv.setText(SharedPreferncesUtil.getNickName(this));

		appIconIv = (RoundCornersImageView) findViewById(R.id.detial_app_icon);
		appNameTv = (TextView) findViewById(R.id.activity_details_app_name);
		awardTv = (TextView) findViewById(R.id.activity_details_app_reward);
		sizeTv = (TextView) findViewById(R.id.activity_details_app_size);
		downBtn = (Button) findViewById(R.id.activity_detail_down_btn);
		appSummaryTv = (TextView) findViewById(R.id.activity_detial_app_summary);

		progressLayout = (LinearLayout) findViewById(R.id.progress_layout);
		downProgressBar = (ProgressBar) findViewById(R.id.downloadbar);
		downProgressBar.setMax(100);
		downPercentTv = (TextView) findViewById(R.id.down_percent_tv);
		downBtn.setVisibility(View.GONE);

		userNameTv.setOnClickListener(this);
		backIv.setOnClickListener(this);
		userInfoMoreIv.setOnClickListener(this);
		downBtn.setOnClickListener(this);
		cashOutBtn.setOnClickListener(this);
		exchangeBtn.setOnClickListener(this);
	}

	// 原有方法加载本地资源
	private View insertImage(Integer id, int Rnum) {
		LinearLayout layout = new LinearLayout(getApplicationContext());
		layout.setLayoutParams(new LayoutParams(250, 370));
		layout.setGravity(Gravity.CENTER);
		ImageView imageView = new ImageView(getApplicationContext());
		imageView.setLayoutParams(new LayoutParams(240, 360));
		imageView.setOnClickListener(this);
		imageView.setId(Rnum);
		imageView.setBackgroundResource(id);

		layout.addView(imageView);
		return layout;
	}

	// 加载网络资源
	private View insertImage(String address, int Rnum) {
		LinearLayout layout = new LinearLayout(getApplicationContext());
		// int width = (int) (ChargeApplication.getScreenWidth() / 2);
		// int height = (int) (ChargeApplication.getScreenHeight() / 2.5);
		layout.setLayoutParams(new LayoutParams(250, 370));
		layout.setGravity(Gravity.CENTER);
		ImageView imageView = new ImageView(getApplicationContext());

		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(240, 360);
		lp.setMargins(16, 0, 0, 0);

		imageView.setId(Rnum);
		imageView.setOnClickListener(this);
		if (Rnum != 0) {
			imageView.setLayoutParams(lp);
		} else {
			imageView.setLayoutParams(new LayoutParams(240, 360));
		}
		String imagePath = StringUtils.formatPicture(address);
		LoadImage.LoadBigPic(imagePath, imageView);
		// layout.addView(imageView);
		return imageView;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() >= 0 && v.getId() < 10) {
			imagebigPopwindow.showPopupWindow(backIv);
			imagebigPopwindow.currentimage(v.getId());
			return;
		}
		switch (v.getId()) {
		case R.id.title_back:
			this.finish();
			break;
		case R.id.tixian_btn:
			Intent it = new Intent(this, CashOutActivity.class);
			startActivity(it);
			break;
		case R.id.exchange_btn:
			Intent its = new Intent(this, ScanActivity.class);
			startActivity(its);
			break;
		case R.id.user_info_more:
			Intent intent = new Intent(this, CenterActivity.class);
			startActivity(intent);
			break;
		case R.id.user_name:
			Intent ite = new Intent(this, ModifyNickNameActivity.class);
			ite.putExtra("nickname", userNameTv.getText().toString());
			startActivity(ite);
			break;
		case R.id.activity_detail_down_btn:
			String text = downBtn.getText().toString();
			if (text.equals("打开")) {
				ApkInfoUtils.openAppByPackageName(this, map.get("PackageName"));
				break;
			} else if (text.equals("安装")) {
				install(NetDetialActivity.this, ChargeApplication.APP_ROOT
						+ FileUtil.getFileName(map.get("DownUrl")));
				break;
			}

			String path = map.get("DownUrl");
			if (mIsPause) {
				if (Environment.MEDIA_MOUNTED.equals(Environment
						.getExternalStorageState())) {
					download(path);
					downBtn.setText("暂停");
					mIsPause = false;
				}
			} else {
				if (mDownloadTask != null) {
					stop();
					downBtn.setText("开始");
					mIsPause = true;
					DownloadManager.getInstance().updateTaskState(
							map.get("DownUrl"), true);
				}
			}
			progressLayout.setVisibility(View.VISIBLE);
			// if (Environment.getExternalStorageState().equals(
			// Environment.MEDIA_MOUNTED)) {
			// download(path, "/mnt/sdcard/manhu/download/");
			// ChargeApplication.installList.put(map.get("PackageName"),
			// map.get("AppID"));
			// progressLayout.setVisibility(View.VISIBLE);
			// downBtn.setVisibility(View.GONE);
			// } else {
			// Toast.makeText(NetDetialActivity.this, "SDCard不存在或者写保护", 1)
			// .show();
			// }

			break;
		}
	}

	private void stop() {
		if (mDownloadTask != null) {
			mDownloadTask.pause();
			mDownloadTask = null;
		}
	}

	private void download(String downUrl) {
		if (mDownloadTask == null) {
			mDownloadTask = new DownloadTask(this);
			DownloadManager.getInstance().add2TaskList(downUrl, mDownloadTask);
			DownloadManager.getInstance().updateTaskState(downUrl, false);
			// mDownloadTask = new DownloadTask();
			mDownloadTask.execute(downUrl, ChargeApplication.APP_ROOT);
		}

		setUpdateListener();
	}

	/**
	 * @描述：
	 */
	private void setUpdateListener() {
		mDownloadTask.setUpdateListener(new UpdateListener() {

			@Override
			public void updateProgress(int size) {
				downProgressBar.setProgress(size);
				downPercentTv.setText(size + "%");
			}

			@Override
			public void onComplete(String path) {
				progressLayout.setVisibility(View.GONE);
				DownloadManager.getInstance().deleteTask(map.get("DownUrl"));
				downBtn.setText("安装");
				userDownRes();
				install(NetDetialActivity.this, path);
			}

			@Override
			public void onError(String error) {

			}

			@Override
			public void onCancle() {

			}
		});
	}

	private void install(Context context, String path) {
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_VIEW);
		File file = new File(path);
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}
	// private Handler handler = new Handler() {
	//
	// public void handleMessage(Message msg) {
	// switch (msg.what) {
	// case 1:
	// downProgressBar.setProgress(msg.getData().getInt("size"));
	// float num = (float) downProgressBar.getProgress()
	// / (float) downProgressBar.getMax();
	// int result = (int) (num * 100);
	// downPercentTv.setText(result + "%");
	// break;
	// case -1:
	// Toast.makeText(NetDetialActivity.this, "下载失败", 1).show();
	// break;
	// case 2:
	// progressLayout.setVisibility(View.GONE);
	// ApkInfoUtils.install(
	// NetDetialActivity.this,
	// "/mnt/sdcard/manhu/download/"
	// + StringUtils.getFileName(msg.obj.toString()));
	// break;
	// }
	// }
	// };
	//
	// /**
	// * @描述：主线程(UI线程) 对于显示控件的界面更新只是由UI线程负责， 如果是在非UI线程更新控件的属性值，更新后的显示界面不会反映到屏幕上
	// * @param path
	// * @param savedir
	// */
	//
	// private void download(final String path, final String savedir) {
	// new Thread(new Runnable() {
	//
	// @Override
	// public void run() {
	// FileDownloader loader = new FileDownloader(
	// NetDetialActivity.this, path, savedir, 4);
	// downProgressBar.setMax(loader.getFileSize());// 设置进度条的最大刻度为文件的长度
	//
	// try {
	// loader.download(new DownloadProgressListener() {
	//
	// @Override
	// public void onDownloadSize(int size) {// 实时获知文件已经下载的数据长度
	// Message msg = new Message();
	// msg.what = 1;
	// msg.getData().putInt("size", size);
	// handler.sendMessage(msg);// 发送消息
	// }
	//
	// public void onDownloadComplete(String path) {
	// Message msg = new Message();
	// msg.what = 2;
	// msg.obj = path;
	// handler.sendMessage(msg);
	// }
	// });
	// } catch (Exception e) {
	// handler.obtainMessage(-1).sendToTarget();
	// }
	// }
	// }).start();
	// }

}
